package com.todo.content.infrastructure.repository.impl;

import com.alibaba.fastjson.JSONObject;
import com.todo.common.common.entity.response.page.PageResult;
import com.todo.common.common.enums.BizErrorCodeEnum;
import com.todo.common.common.exception.BizException;
import com.todo.common.utils.MathUtils;
import com.todo.content.infrastructure.convert.ContentConvert;
import com.todo.content.infrastructure.entity.condition.ContentInfoCondition;
import com.todo.content.infrastructure.entity.domain.ContentDetailDO;
import com.todo.content.infrastructure.entity.po.ContentBaseRelationPO;
import com.todo.content.infrastructure.entity.po.ContentInfoPO;
import com.todo.content.infrastructure.mapper.ContentBaseRelationMapper;
import com.todo.content.infrastructure.mapper.ContentInfoMapper;
import com.todo.content.infrastructure.repository.ContentInfoRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import com.google.common.collect.Lists;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * (ContentInfo)表服务实现类
 *
 * @author zhangwenxiang
 * @since 2024-03-04 21:10:04
 */
@Slf4j
@Repository("contentInfoRepository")
public class ContentInfoRepositoryImpl implements ContentInfoRepository {
    @Resource
    private ContentInfoMapper contentInfoMapper;
    @Resource
    private ContentBaseRelationMapper contentBaseRelationMapper;


    @Override
    public PageResult<ContentInfoPO> queryContentInfoByCondition(ContentInfoCondition contentInfoCondition) {
        PageResult<ContentInfoPO> pageResult = new PageResult<>();
        if (contentInfoCondition == null) {
            throw new BizException(BizErrorCodeEnum.DATA_NOT_EXIST);
        }
        pageResult.setPageNum(contentInfoCondition.getPageIndex());
        pageResult.setPageSize(contentInfoCondition.getPageSize());
        long count = queryCountByCondition(contentInfoCondition);
        if (count <= 0) {
            return pageResult;
        }
        pageResult.setPageCount((int) MathUtils.divide(count, contentInfoCondition.getPageSize()));
        pageResult.setTotal(count);
        List<ContentInfoPO> sightPoiPOList = contentInfoMapper.queryContentInfoByCondition(contentInfoCondition);
        if (CollectionUtils.isEmpty(sightPoiPOList)) {
            pageResult.setHasNext(false);
            return pageResult;
        }
        pageResult.setResults(sightPoiPOList);
        pageResult.setCurrentIndex(sightPoiPOList.get(0).getId());
        pageResult.setHasNext(sightPoiPOList.size() >= contentInfoCondition.getPageSize());
        return pageResult;
    }

    @Override
    public Long queryCountByCondition(ContentInfoCondition contentInfoCondition) {
        if (contentInfoCondition == null || contentInfoCondition.getPageSize() <= 0) {
            throw new BizException(BizErrorCodeEnum.DATA_NOT_EXIST);
        }
        return contentInfoMapper.queryCountByCondition(contentInfoCondition);
    }

    @Override
    @Transactional
    public Boolean insertContentDetail(ContentDetailDO contentDetailDO) {
        if (contentDetailDO == null || contentDetailDO.getContentInfo() == null) {
            throw new BizException(BizErrorCodeEnum.PARAM_ERROR);
        }
        if (!baseFieldCheck(contentDetailDO)) {
            return false;
        }
        ContentInfoPO contentInfoPO = ContentConvert.buildContentInfoPO(contentDetailDO);
        if (contentInfoPO == null) {
            throw new BizException(BizErrorCodeEnum.PARAM_ERROR);
        }
        int infoResult = contentInfoMapper.insertContentInfoPO(contentInfoPO);
        if (infoResult == 0) {
            return false;
        }
        if (CollectionUtils.isEmpty(contentDetailDO.getContentRelationList())) {
            return true;
        }
        List<ContentBaseRelationPO> contentBaseRelationPOList = ContentConvert.buildContentRelationList(contentDetailDO);
        int relationResult = contentBaseRelationMapper.insertBatch(contentBaseRelationPOList);
        if (relationResult == 0) {
            throw new BizException(BizErrorCodeEnum.SYSTEM_ERROR);
        }
        return true;
    }


    @Override
    public Boolean updateContentDetailById(ContentDetailDO contentDetailDO, Boolean updateCount) {
        if (contentDetailDO == null || contentDetailDO.getContentInfo() == null) {
            throw new BizException(BizErrorCodeEnum.PARAM_ERROR);
        }
        if (!baseFieldCheck(contentDetailDO)) {
            return false;
        }
        ContentInfoPO contentInfoPO = ContentConvert.buildContentInfoPO(contentDetailDO);
        if (contentInfoPO == null) {
            throw new BizException(BizErrorCodeEnum.PARAM_ERROR);
        }
        int infoResult = contentInfoMapper.updateContentInfoPOById(contentInfoPO);
        if (infoResult == 0) {
            return false;
        }
        //如果主要是更新数据的则可以退出，不操作关联数据
        if (CollectionUtils.isEmpty(contentDetailDO.getContentRelationList()) || updateCount) {
            return true;
        }
        // 更新先清除历史关联数据再新增
        int removeResult = contentBaseRelationMapper.removeContentBaseRelationByContentId(contentDetailDO.getId());
        if (removeResult == 0) {
            throw new BizException(BizErrorCodeEnum.SYSTEM_ERROR);
        }
        List<ContentBaseRelationPO> contentBaseRelationPOList = ContentConvert.buildContentRelationList(contentDetailDO);
        int relationResult = contentBaseRelationMapper.insertBatch(contentBaseRelationPOList);
        if (relationResult == 0) {
            throw new BizException(BizErrorCodeEnum.SYSTEM_ERROR);
        }
        return true;
    }

    @Override
    @Transactional
    public Boolean removeContentById(Long id) {
        if (id == null || id < 0) {
            throw new BizException(BizErrorCodeEnum.PARAM_ERROR);
        }
        int infoResult = contentInfoMapper.removeContentInfoPOById(id);
        if (infoResult == 0) {
            throw new BizException(BizErrorCodeEnum.SYSTEM_ERROR);
        }
        int removeResult = contentBaseRelationMapper.removeContentBaseRelationByContentId(id);
        if (removeResult == 0) {
            throw new BizException(BizErrorCodeEnum.SYSTEM_ERROR);
        }
        return true;
    }

    @Override
    public ContentInfoPO queryContentInfoPOById(Long id) {
        if (id == null || id < 0) {
            return null;
        }
        return contentInfoMapper.queryContentInfoPOById(id);
    }

    @Override
    public ContentDetailDO queryContentDetailById(Long id) {
        ContentInfoPO contentInfoPO = queryContentInfoPOById(id);
        if (contentInfoPO == null) {
            return null;
        }
        List<ContentBaseRelationPO> contentBaseRelationPOList = queryContentBaseRelationPOByContentId(id);
        ContentDetailDO contentDetailDO = ContentConvert.convertToContentDetailDO(contentInfoPO, contentBaseRelationPOList);
        return contentDetailDO;
    }

    @Override
    public List<ContentBaseRelationPO> queryContentBaseRelationPOByContentId(Long contentId) {
        if (contentId == null || contentId < 0) {
            return Lists.newArrayList();
        }
        return contentBaseRelationMapper.queryContentBaseRelationPOByContentId(contentId);
    }

    @Override
    public Boolean updateContentStatus(Long contentId, Integer oldType, Integer newType) {
        if (contentId == null || contentId < 0 || oldType == null || newType == null) {
            throw new BizException(BizErrorCodeEnum.PARAM_ERROR);
        }
        return contentInfoMapper.updateContentStatus(contentId, oldType, newType);
    }

    @Override
    public List<ContentInfoPO> queryContentInfoByIdList(List<Long> contentIdList) {
        if (CollectionUtils.isEmpty(contentIdList)) {
            return Lists.newArrayList();
        }
        return contentInfoMapper.queryContentInfoByIdList(contentIdList);
    }

    @Override
    @Transactional
    public Boolean removeContentByIdList(List<Long> contentIdList) {
        if (CollectionUtils.isEmpty(contentIdList)) {
            return true;
        }
        Boolean contentResult = contentInfoMapper.removeContentByIdList(contentIdList);
        if (!contentResult) {
            return false;
        }
        Boolean relationResult = contentBaseRelationMapper.removeContentBaseRelationByContentIdList(contentIdList);
        if (!relationResult) {
            throw new BizException(BizErrorCodeEnum.SYSTEM_ERROR);
        }
        return true;
    }

    @Override
    public Boolean updateContentPrivateType(Long contentId, Integer type) {
        if (contentId == null || contentId < 0 || type == null) {
            return false;
        }
        return contentInfoMapper.updateContentPrivateType(contentId, type);
    }

    @Override
    public Boolean updateContentCommitType(Long contentId, Integer type) {
        if (contentId == null || contentId < 0 || type == null) {
            return false;
        }
        return contentInfoMapper.updateContentCommitType(contentId, type);
    }

    private boolean baseFieldCheck(ContentDetailDO contentDetailDO) {
        if (contentDetailDO == null || contentDetailDO.getContentInfo() == null || contentDetailDO.getUserId() == null) {
            log.info("ContentInfoRepository#baseFieldCheck 核心数据操作失败，基础数据为空 contentDetailDO：【{}】", JSONObject.toJSONString(contentDetailDO));
            return false;
        }
        ContentDetailDO.ContentInfo contentInfo = contentDetailDO.getContentInfo();
        if (contentInfo.getTitle() == null || contentInfo.getContent() == null || contentInfo.getStatus() == null || contentInfo.getClassifyCode() == null) {
            log.info("ContentInfoRepository#baseFieldCheck 内容数据操作失败，基础数据为空 contentDetailDO：【{}】", JSONObject.toJSONString(contentDetailDO));
            return false;
        }
        List<ContentDetailDO.ContentRelation> contentRelationList = contentDetailDO.getContentRelationList();
        if (CollectionUtils.isNotEmpty(contentRelationList)) {
            for (ContentDetailDO.ContentRelation contentRelation : contentRelationList) {
                if (contentRelation.getRelationType() == null || contentRelation.getIsOutside() == null) {
                    log.info("ContentInfoRepository#baseFieldCheck 关联数据操作失败，基础数据为空 contentDetailDO：【{}】", JSONObject.toJSONString(contentDetailDO));
                    return false;
                }
                if (contentRelation.getIsOutside() == 1 && contentRelation.getJumpUrl() == null) {
                    log.info("ContentInfoRepository#baseFieldCheck 关联数据操作失败，站外数据跳转链接为空 contentDetailDO：【{}】", JSONObject.toJSONString(contentDetailDO));
                    return false;
                }
            }
        }
        return true;
    }
}
